var Py = Py || {};
Py.Shop = (function () {
    var methods = {},
        id = 'shopcart',
        $shop_cart,
        $current_parent,
        opening = false;

    var $popup = $('<div id="py-shop-popup-wrap"></div>');
    var $submit = $('<button id="py-shop-ok" class="transition">Ok</button>');
    var $close = $('<a href="#" id="py-shop-cancel" class="transition">X</a>');
    var $input = $('<input type="text" id="py-shop-q-input" value="1"/>');
    var $p_id = $('<input type="hidden" id="py-shop-phone-id">'); // Mã điện thoại đang lựa chọn
    var $form = $('<form id="py-shop-popup-form"></form>').append(
        $('<label>Số lượng</label>'),
        $input,
        $submit,
        $p_id
    );

    $close.click(function(event) {
        event.preventDefault();
        methods.close();
    });

    $form.submit(function (event){
        event.preventDefault();

        // Kiểm tra số lượng hợp lệ
        if (isNaN($input.val()) || $input.val() <= 0) {
            jModal.open({
                content: 'Vui lòng nhập số lượng hợp lệ!',
                title: 'Đặt hàng',
                type: 'error',
                on_close: function() {
                    $input.focus();
                }
            });
        } else {
            var current_offset = $(document).scrollTop();
            var call_ajax_completed = false;
            var ajax_handler;
            jModal.open({
                content: 'Vui lòng đợi giây lát',
                title: 'Thêm giỏ hàng',
                loading: true,
                on_cancel: function() {
                    ajax_handler && ajax_handler.abort();
                }
            });
            var offset = $shop_cart.offset().top - 100 ;
            if ($shop_cart.height() > $(window).height() - 150) {
                offset += $shop_cart.height() - 300
            }
            Py.scrollTo(offset, 400, function() {
                setTimeout(function() {
                    ajax_handler = $.post(Py.markUpUrl('shop/add'), {
                        id: $p_id.val(),
                        quantity: $input.val()
                    }, function(data) {
                        console.log(data);
                        jModal.close(100);
                        Py.Shop.change(data['html']);
                        call_ajax_completed = true;
                    }, 'json');

                    setTimeout(function() {
                        Py.scrollTo(current_offset, 500, function() {
                            Py.Shop.close();
                        });
                    }, 2000);
                }, 300);
            });
        }
    });

    $popup.append($form, $close.hide());


    methods.change = function (html, no_effect) {
        if (no_effect) {
            $shop_cart.html(html);
        } else {
            $shop_cart.slideUp(500, function () {
                $shop_cart.html(html).slideDown(500);
            });
        }
    };

    methods._popup = function($element) {
        $element.after($popup);
        $current_parent = $element.parent().addClass('py-shop-popup-parent');
        $p_id.val($element.metadata().id);
        $popup.slideDown(400, function() {
            $close.css('left', '90px').show(300, function() {
                $(this).css('left', $form.width())
            });
        });

        opening = true;
    };

    methods.popup = function($element) {
        if (opening) {
            methods.close(100, methods._popup, $element);
        } else {
            methods._popup($element);
        }

    };

    methods.close = function($timeout, callback, $element) {
        $timeout || ($timeout = 200);
        $close.hide($timeout, function() {
            $popup.slideUp($timeout + 100, function() {
                $current_parent && $current_parent.removeClass('py-shop-popup-parent');

                callback && callback($element);
            });
        });
        opening = false;
    };

    // Initial functions
    $(document).ready(function () {
        $('a.buy-link').click(function (event) {
            event.preventDefault();
            methods.popup($(this));
        });

        // get shop cart element
        $shop_cart = $('#' + id);

        // Handle remove item link click event
        $('a.shop-remove-item').live('click', function(event) {
            event.preventDefault();
            var p_id = $(this).metadata().id;
            var ajax_handler, ajax_call_completed = false;
            ajax_handler = $.post(Py.markUpUrl('shop/remove'), {id: p_id}, function(data){
                console.log(data);
                $('#item-' + p_id).fadeOut(500, function(){
                    Py.Shop.change(data['html'], true);
                    ajax_call_completed = true;
                    jModal.close();
                });
            },  'json');

            ajax_call_completed || jModal.open({
                content: 'Vui lòng đợi giây lát',
                title: 'Xóa điện thoại',
                loading: true,
                on_cancel: function() {
                    ajax_handler && ajax_handler.abort();
                }
            });
        });

        // Handle clear shop cart link click event
        $('#shop-clear').live('click', function(event) {
            event.preventDefault();
            var ajax_handler, ajax_call_completed = false;
            $.post(Py.markUpUrl('shop/clear'), function(data){
                Py.Shop.change(data['html']);
                ajax_call_completed = true;
                jModal.close();
            }, 'json');

            ajax_call_completed || jModal.open({
                content: 'Vui lòng đợi giây lát',
                title: 'Xóa giỏ hàng',
                loading: true,
                on_cancel: function() {
                    ajax_handler && ajax_handler.abort();
                }
            });
        });
    });


    return methods;
})();